/**
 * 日志相关接口-RestFull风格
 * 包括： 新增、删除、查询日志
 * 
 * RestFull风格
 * 请求方式的不同
 *      get: 查询
 *      post：增加
 *      put：修改
 *      delete: 删除
 * 请求路径携带参数的不同：
 *      路径通过动态参数方式传参
 *      举例：
 *          后端：/petDairy/get/:id
 *          前端：/petDairy/get/1
 */
const express = require('express')
// 创建路由对象
const router = express.Router()
// 引入数据库连接池
const pool = require('../../db/db')
// 引入joi表单校验
const Joi = require('joi')
// 引入Response
const Response = require('../../utils/ResponseData')

/**
 * 新增日志
 * url:http://localhost:3000/petDatiry/add
 * method: POST
 * params: req.body
 */
router.post('/petDatiry/add', (req, res) => {
    // 解构表单数据
    let { d_img, d_man_name, d_city, d_time, d_detail } = req.body
    // 校验规则
    let schema = Joi.object({
        d_img: Joi.string().required(),
        d_man_name: Joi.string().required(),
        d_city: Joi.string().required(),
        d_time: Joi.required(),
        d_detail: Joi.string().required()
    })
    // 校验
    let { error, value } = schema.validate(req.body)
    if (error) {
        res.send(Response.error(error))
        return
    }
    // 编写sql
    const sql = `insert into pet_diary set ?`
    pool.query(sql, { d_img, d_man_name, d_city, d_time, d_detail }, (err, result) => {
        if (err) {
            res.send(Response.error('日志添加失败！'))
            return
        }
        if (result && result.affectedRows > 0) {
            res.send(Response.success('日志添加成功！'))
        }
    })
})

/**
 * 日志列表接口： 模糊 + 分页
 * 
 */
router.get('/petDairy/get/:page/:pageSize/:keywords', async (req, res) => {
    // 解构获取的参数
    let { page, pageSize, keywords } = req.params
    console.log(keywords, '====');
    // 校验规则
    let schema = Joi.object({
        page: Joi.number().required(),
        pageSize: Joi.number().max(10).required(),
        keywords: Joi.string().required()
    })
    // 校验
    let { error, value } = schema.validate(req.params)

    if (error) {
        res.send(Response.error(error))
        return
    }
    try {

        // 根据当前页和每页显示条数，计算开始位置
        const startIndex = (page - 1) * pageSize
        pageSize = parseInt(pageSize)
        page = page ? parseInt(page) : 1
        if (keywords == "''") keywords = ''
        // 编写sql
        const sql = `select * from (select * from pet_diary where d_man_name like ? or d_city like ?) d1 limit ?,?`
        // 执行sql
        let result = await pool.querySync(sql, [`%${keywords}%`, `%${keywords}%`, startIndex, pageSize])
        // 编写sql，查询总条数
        const sql2 = `select count(d_id) as count from (select * from pet_diary where d_man_name like ? or d_city like ?) d1`
        // 执行sql
        let result2 = await pool.querySync(sql2, [`%${keywords}%`, `%${keywords}%`])
        // 获取总条数
        const total = result2[0].count
        // 计算总页数
        const maxPage = Math.ceil(total / pageSize)

        res.send(Response.success({ page, pageSize, total, maxPage, result }))
    } catch (e) {
        console.log(e);
        res.send(Response.error(e))
    }

})

// 删除日志
router.delete('/petDairy/delete/:id', (req, res) => {
    console.log(req.params,'******');
    let { id } = req.params
    // 校验规则
    let scheam = Joi.object({
        id: Joi.number().required()
    })
    // 校验
    let { error } = scheam.validate(req.params)
    if (error) {
        res.send(Response.error(error))
        return
    }
    // 编写sql
    let sql = `delete from pet_diary where d_id=?`
    // 执行sql
    pool.query(sql, [id], (err, result) => {
        if (result && result.affectedRows > 0) {
            res.send(Response.success(null, '日志信息删除成功'))
        } else {
            res.send(Response.error('日志信息删除失败！'))
        }
    })
})


module.exports = router